package com.zuowei.ycy.user.ui.index;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.and.yzy.frame.adapter.CommonAdapter;
import com.and.yzy.frame.adapter.ViewHolder;
import com.and.yzy.frame.util.RetrofitUtils;
import com.zuowei.ycy.R;
import com.zuowei.ycy.user.adapter.GoodInfoAdapter;
import com.zuowei.ycy.user.config.UserManger;
import com.zuowei.ycy.user.domain.GoodInfo;
import com.zuowei.ycy.user.domain.SortKey;
import com.zuowei.ycy.user.http.Merchant;
import com.zuowei.ycy.ui.BaseToolbarAty;
import com.zuowei.ycy.user.util.AppJsonUtil;
import com.zuowei.ycy.user.util.PtrInitHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 分类列表
 */
public class GoodSortAty extends BaseToolbarAty {

    @Bind(R.id.lv_data)
    ListView mLvData;

    @Bind(R.id.ptr_frame)
    PtrFrameLayout mPtrFrame;
    @Bind(R.id.tv_tab_01)
    TextView mTvTab01;
    @Bind(R.id.iv_tab_01)
    ImageView mIvTab01;
    @Bind(R.id.tv_tab_02)
    TextView mTvTab02;
    @Bind(R.id.iv_tab_02)
    ImageView mIvTab02;
    @Bind(R.id.tv_tab_03)
    TextView mTvTab03;
    @Bind(R.id.iv_tab_03)
    ImageView mIvTab03;
    @Bind(R.id.ll_empty)
    LinearLayout ll_empty;



    private List<TextView> tabs;
    private List<ImageView> ivs;

    private PopupWindow mWindow;

    private List<SortKey> StringTab01;
    private List<SortKey> StringTab02;
    private List<SortKey> StringTab03;

    private int tabType = 0;

    private CommonAdapter<SortKey> mPopAdapter;


    private GoodInfoAdapter infoAdapter;
    /**
     * 分类
     */
    private String merchant_type_id = "0";

    /**
     * 排序
     */
    private String sort_order = "5";

    @Override
    public int getLayoutId() {
        return R.layout.index_sort_layout;
    }

    @Override
    public void initData() {
        mToolbar.setTitle("分类");


        merchant_type_id = getIntent().getExtras().getString("merchant_type_id", "0");

        mTvTab02.setText(getIntent().getExtras().getString("merchant_type_name", "分类"));

        initPop();

        tabs = new ArrayList<>();

        tabs.add(mTvTab01);
        tabs.add(mTvTab02);
        tabs.add(mTvTab03);

        ivs = new ArrayList<>();
        ivs.add(mIvTab01);
        ivs.add(mIvTab02);
        ivs.add(mIvTab03);


        PtrInitHelper.initPtr(this, mPtrFrame);
        mPtrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {


                doHttp(RetrofitUtils.createApi(Merchant.class).merchantTypePage(merchant_type_id, UserManger.getBaiDuLon(), UserManger.getBaiDuLat(), sort_order), 1);


            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mLvData, header);
            }
        });

        mLvData.setEmptyView(ll_empty);
        mLvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                GoodInfo goodInfo= (GoodInfo) parent.getItemAtPosition(position);

                Bundle bundle=new Bundle();
                bundle.putString("merchant_id",goodInfo.getMerchant_id());
                bundle.putString("shop_name",goodInfo.getShop_name());
                startActivity(BusinessTabAty.class, bundle);
            }
        });
    }


    private void initPop() {

        mWindow = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        View pop = getLayoutInflater().inflate(R.layout.index_sort_pop, null, false);

        ListView listView = (ListView) pop.findViewById(R.id.lv_pop);
        LinearLayout ll_close = (LinearLayout) pop.findViewById(R.id.ll_close);
        View dismiss = pop.findViewById(R.id.v_dismiss);
        ll_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mWindow.dismiss();
                hideIvs();
            }
        });
        dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mWindow.dismiss();
                hideIvs();
            }
        });

        StringTab01 = new ArrayList<>();

        StringTab03 = new ArrayList<>();

        StringTab01.add(new SortKey("综合排序", true));
        StringTab01.add(new SortKey("销量最高", false));
        StringTab01.add(new SortKey("速度最快", false));
        StringTab01.add(new SortKey("评分最高", false));
        StringTab01.add(new SortKey("距离最近", false));


        StringTab03.add(new SortKey("配送最快", false));
        StringTab03.add(new SortKey("评价最高", false));


        mPopAdapter = new CommonAdapter<SortKey>(this, StringTab01, R.layout.index_sort_pop_item) {
            @Override
            public void convert(ViewHolder holder, final SortKey item, int positon) {

                holder.setTextViewText(R.id.tv_sort, item.getMerchant_type_name());

                if (item.isSelect()) {

                    holder.setTextViewTextColor(R.id.tv_sort, getResources().getColor(R.color.toolbar_bg));
                } else {

                    holder.setTextViewTextColor(R.id.tv_sort, getResources().getColor(R.color.black_gray));
                }


                holder.setOnClick(R.id.tv_sort, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        for (SortKey data : mDatas) {
                            if (item != data) {
                                data.setIsSelect(false);
                            } else {
                                data.setIsSelect(true);
                            }
                        }


                        switch (tabType) {
                            case 0:
                                mTvTab01.setText(item.getMerchant_type_name());
                                break;
                            case 1:
                                mTvTab02.setText(item.getMerchant_type_name());
                                merchant_type_id = item.getMerchant_type_id();
                                break;
                            case 2:
                                mTvTab03.setText(item.getMerchant_type_name());
                                break;
                        }


                        if (tabType != 1) {
                            switch (item.getMerchant_type_name()) {
                                case "综合排序":
                                    sort_order = "0";
                                    break;
                                case "销量最高":
                                    sort_order = "1";
                                    break;
                                case "速度最快":
                                    sort_order = "2";
                                    break;
                                case "评分最高":
                                case "评价最高":
                                    sort_order = "3";
                                    break;
                                case "距离最近":
                                    sort_order = "4";
                                    break;
                                case "配送最快":
                                    sort_order = "5";
                                    break;

                            }
                        }


                        mWindow.dismiss();
                        hideIvs();
                        notifyDataSetChanged();

                        //请求网络

                        showLoadingContentDialog(96, 0);
                        doHttp(RetrofitUtils.createApi(Merchant.class).merchantTypePage(merchant_type_id, UserManger.getBaiDuLon(), UserManger.getBaiDuLat(), sort_order), 1);


                    }
                });

            }
        };

        listView.setAdapter(mPopAdapter);

        mWindow.setContentView(pop);
        mWindow.setOutsideTouchable(true);
        mWindow.setBackgroundDrawable(new BitmapDrawable());


    }


    private void hideIvs() {

        mIvTab01.setVisibility(View.INVISIBLE);
        mIvTab02.setVisibility(View.INVISIBLE);
        mIvTab03.setVisibility(View.INVISIBLE);
    }


    @OnClick({R.id.rl_tab_01, R.id.rl_tab_02, R.id.rl_tab_03})
    @Override
    public void btnClick(View view) {
        super.btnClick(view);
        switch (view.getId()) {
            case R.id.rl_tab_01:

                tabType = 0;
                updateTab(mTvTab01);

                mPopAdapter.setDatas(StringTab01);
                mWindow.showAsDropDown(mTvTab01);

                break;
            case R.id.rl_tab_02:
                if (StringTab02 == null) {

                    showToast("暂无分类");
                } else {
                    tabType = 1;
                    updateTab(mTvTab02);
                    mPopAdapter.setDatas(StringTab02);
                    mWindow.showAsDropDown(mTvTab01);
                }

                break;
            case R.id.rl_tab_03:
                tabType = 2;
                updateTab(mTvTab03);
                mPopAdapter.setDatas(StringTab03);
                mWindow.showAsDropDown(mTvTab01);
                break;


        }

    }

    private void updateTab(TextView view) {

        for (int i = 0; i < tabs.size(); i++) {

            if (tabs.get(i) == view) {

                tabs.get(i).setTextColor(getResources().getColor(R.color.toolbar_bg));
                tabs.get(i).setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.shangjiatou2), null);
                ivs.get(i).setVisibility(View.VISIBLE);
            } else {

                tabs.get(i).setTextColor(getResources().getColor(R.color.black_gray));
                tabs.get(i).setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.xiaojiantou), null);
                ivs.get(i).setVisibility(View.INVISIBLE);
            }


        }


    }

    @Override
    public boolean setIsInitRequestData() {
        return true;
    }

    @Override
    public void requestData() {

        showLoadingContentDialog(96, 0);

        doHttp(RetrofitUtils.createApi(Merchant.class).merchantTypePage(merchant_type_id, UserManger.getBaiDuLon(), UserManger.getBaiDuLat(), sort_order), 1);


    }

    @Override
    public void onError(Call<ResponseBody> call, Throwable t, int what) {
        mPtrFrame.refreshComplete();
        super.onError(call, t, what);
    }

    @Override
    public void onFailure(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {
        mPtrFrame.refreshComplete();
        super.onFailure(result, call, response, what);
    }

    @Override
    public void onSuccess(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {


        switch (what) {
            case 1:

                if (StringTab02 == null) {

                    StringTab02 = AppJsonUtil.getArrayList(result, "merchant_type_list", SortKey.class);
                } else {
                    StringTab02.clear();
                    StringTab02 = AppJsonUtil.getArrayList(result, "merchant_type_list", SortKey.class);
                    if (tabType == 1) {
                        mPopAdapter.setDatas(StringTab02);

                    }
                }


                if (infoAdapter == null) {

                    infoAdapter = new GoodInfoAdapter(this, AppJsonUtil.getArrayList(result, "merchant_list", GoodInfo.class), R.layout.index_good_item);
                    mLvData.setAdapter(infoAdapter);
                } else {
                    infoAdapter.removeAll();
                    infoAdapter.addAll(AppJsonUtil.getArrayList(result, "merchant_list", GoodInfo.class));
                }



                mPtrFrame.refreshComplete();


                break;
            case 2:

                break;
        }


        super.onSuccess(result, call, response, what);
    }
}
